﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CarbonExchange.WebControls;
using CarbonExchange.Bll;
using System.Web.Security;

public partial class Templates_Profile_ActivateEmail : PageBase
{
    protected void Page_Load(object sender, EventArgs e)
    {
        btnSubmit.Click += new EventHandler(btnSubmit_Click);
        if (!IsPostBack)
        {
            string code = Request.QueryString["Code"];
            var tmp = Acms.Bll.EmailActivationCode.GetByCodeAndSiteId(code, AcmsContext.SiteId);
            if (tmp != null)
            {
                Code = tmp.Code;
                lblEmail.Text = tmp.EmailAddress;
                pnlForm.Visible = true;
                pnlNotFound.Visible = false;
            }
            else
            {
                lblCodeNotFound.Text = code;
                pnlForm.Visible = false;
                pnlNotFound.Visible = true;
            }
            DataBind();
        }
    }

    void btnSubmit_Click(object sender, EventArgs e)
    {
        var user = Acms.Bll.User.GetByEmailActivationCodeAndSiteId(Code, AcmsContext.SiteId);
        if (user != null)
        {
            var result = user.ActivateEmailAddress(Code, txtPassword.Text);
            if (result.Status == Acms.Bll.User.ActivateEmailAddressResult.Results.Success)
            {
                if (!Request.IsAuthenticated)
                {
                    //Login
                    CarbonExchange.Logger.ILogger logger = StructureMap.ObjectFactory.GetInstance<CarbonExchange.Logger.ILogger>();
                    logger.Info(string.Format("Logging in '{0}'", user.EmailAddress));

                    Guid key = user.GetLoginKey(false);
                    HttpCookie authCookie = FormsAuthentication.GetAuthCookie(key.ToString(), false);

                    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);

                    //create new ticket to include the userdata field
                    FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, key.ToString());

                    authCookie.Value = FormsAuthentication.Encrypt(newTicket);
                    Response.Cookies.Add(authCookie);
                }
                //Go to home page
                AcmsContext.RedirectToUrl("~/default.aspx", this);
            }
            else
            {
                pnlIncorrect.Visible = true;
            }
        }
        else
        {
            pnlIncorrect.Visible = true;
        }
    }

    private string Code
    {
        get { return ViewState["Code"] as string; }
        set { ViewState["Code"] = value; }
    }

}
